<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon></el-alert>
      <!-- 选择商品分类区 -->
      <el-row style="margin:15px 0">
        <el-col>
          <span style="font-size:18px">选择商品分类：</span>
          <!-- 级联选择器 -->
          <el-cascader v-model="selectdKeys" :placeholder="manyTableData.attr_name" :options="goodsIficationList" :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children', }"
            @change="JLhandleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="ShuXdialogVisible=true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <!-- 参数标签 -->
              <template slot-scope="scope">
                <el-tag style="margin:0 10px;" v-for="(item,i) in scope.row.attr_vals " :key="i" v-show="item" closable @close="handleClose(i, scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template scope="scope">
                <!-- 编辑按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="small" @click="commoditiesEditor(scope.row.attr_id)">编辑</el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteClassification(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="配置管理" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="ShuXdialogVisible=true">添加属性</el-button>
          <!--静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <!-- 参数标签 -->
              <template slot-scope="scope">
                <el-tag style="margin:0 10px;" v-for="(item,i) in scope.row.attr_vals " :key="i" v-show="item" closable @close="handleClose(i, scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 编辑按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="small" @click="commoditiesEditor(scope.row.attr_id)">编辑</el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteClassification(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加属性对话框 -->
    <el-dialog :title="this.activeName==='many'?'添加动态参数':'添加静态属性'" :visible.sync="ShuXdialogVisible" width="50%" @close="ShuXhandleClose">
      <el-form :model="addForms" :rules="addFormRules" ref="addFormRuleFormref" label-width="100px">
        <el-form-item :label="this.activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="addForms.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ShuXdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="additiveAttribute">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑属性对话框 -->
    <el-dialog :title="this.activeName==='many'?'编辑动态参数':'编辑静态属性'" :visible.sync="editShuXdialogVisible" width="50%" @close="ShuXhandleClose">
      <el-form :model="editaddForms" :rules="addFormRules" ref="addFormRuleFormref" label-width="100px">
        <el-form-item :label="this.activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="editaddForms.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editShuXdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editTtiveAttribute">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'Params',
    data () {
      return {
        // 商品列表数据
        goodsIficationList: [],
        // 选中的父级分类数组
        selectdKeys: [],
        // 默认标签页展示
        activeName: 'many',
        // 添加属性对话框
        ShuXdialogVisible: false,
        // 编辑属性对话框
        editShuXdialogVisible: false,

        // 添加属性的数据
        addForms: {
          attr_name: ''
        },
        // 修改的表单数据对象
        editaddForms: {},
        // 动态参数数据
        manyTableData: [],
        // 静态属性数据
        onlyTableData: [],
        addFormRules: {
          attr_name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' }
          ]
        }
      }
    },
    created () {
      // 商品分类数据列表
      this.ificationList()
    },
    methods: {
      async ificationList () {
        const { data: res } = await this.$http.get('categories')
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品列表失败')
        }
        // this.$message.success('获取商品列表成功')
        this.goodsIficationList = res.data
        // console.log(this.goodsIficationList);
      },
      // 监听级联选择器
      JLhandleChange () {
        this.getCanShuLiBiao()
      },
      // 请求参数列表
      async getCanShuLiBiao () {
        if (this.selectdKeys.length !== 3) {
          this.selectdKeys = []
          this.manyTableData = []
          this.onlyTableData = []
          return
        }
        console.log(this.selectdKeys);
        const { data: res } = await this.$http.get(`categories/${this.isGoodsId}/attributes`, { params: { sel: this.activeName } })
        if (res.meta.status !== 200) {
          return this.$message.error('请求参数列表失败')
        }
        // this.$message.success('请求参数列表成功')

        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.split(',')
          // 控制文本框的显示与隐藏
          item.inputVisible = false
          // 文本框中输入的值
          item.inputValue = ''
          // console.log(res.data);
        });
        if (this.activeName === 'many') {
          this.manyTableData = res.data
        } else {
          this.onlyTableData = res.data
        }
      },
      // 监听标签页标签栏切换事件
      async handleTabClick () {
        this.getCanShuLiBiao()
        // console.log(this.activeName);
      },
      // 监听对话框关闭事件
      ShuXhandleClose () {
        this.$refs.addFormRuleFormref.resetFields()
      },

      // 获取添加属性数据
      additiveAttribute () {
        this.$refs.addFormRuleFormref.validate(async valid => {
          if (!valid) return
          const { data: res } = await this.$http.post(`categories/${this.isGoodsId}/attributes`, { attr_name: this.addForms.attr_name, attr_sel: this.activeName })
          if (res.meta.status !== 201) {
            return this.$message.error('加添属性失败')
          }
          this.$message.success('加添属性成功')
          this.ShuXdialogVisible = false
          this.getCanShuLiBiao()
        })
      },
      getFocus () {
        this.getCanShuLiBiao()
      },

      // // 点击编辑按钮获取分类Id
      async commoditiesEditor (cat_id) {
        const { data: res } = await this.$http.get(`categories/${this.isGoodsId}/attributes/${cat_id}`, { params: { attr_sel: this.activeName } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取ID失败')
        }
        this.editaddForms = res.data
        this.editShuXdialogVisible = true;

      },

      // 删除分类属性
      async deleteClassification (attr_id) {
        const confirmResult = await this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除！')
        }
        // 删除的业务逻辑
        const { data: res } = await this.$http.delete(
          `categories/${this.isGoodsId}/attributes/${attr_id}`
        )

        if (res.meta.status !== 200) {
          return this.$message.error('删除参数失败！')
        }

        this.$message.success('删除参数成功！')
        this.getCanShuLiBiao()
      },
      // 编辑分类数据
      editTtiveAttribute () {
        this.$refs.addFormRuleFormref.validate(async valid => {
          if (!valid) return
          const { data: res } = await this.$http.put(`categories/${this.isGoodsId}/attributes/${this.editaddForms.attr_id}`, { attr_name: this.editaddForms.attr_name, attr_sel: this.activeName })
          console.log(res);
          if (res.meta.status !== 200) {
            return this.$message.error('编辑失败')
          }
          this.$message.success('编辑成功')
          this.getCanShuLiBiao()
          this.editShuXdialogVisible = false
        })
      },
      // 获取参数标签的ID
      async saveAttrVals (row) {
        const { data: res } = await this.$http.put(
          `categories/${this.isGoodsId}/attributes/${row.attr_id}`,
          {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: row.attr_vals.join(',')
          })
        if (res.meta.status !== 200) {
          return
        }
      },
      // 键盘按下Enter键和失去焦点
      async handleInputConfirm (row) {
        if (row.inputValue.trim().length === 0) {
          row.inputValue = ''
          row.inputVisible = false
          return
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        this.saveAttrVals(row)
      },
      // 点击按钮，展示文本输入框
      showInput (row) {
        row.inputVisible = true
        // this.$nextTick作用是当页面重新渲染完成，才会执行下面的代码
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
        // console.log(this);
      },
      // 删除属性标签
      handleClose (i, row) {
        // splice()删除数组的第一项
        row.attr_vals.splice(i, 1)
        this.saveAttrVals(row)
      },

    },
    computed: {
      // 如果按钮需要被禁用，则返回true，否则返回false
      isBtnDisabled () {
        if (this.selectdKeys.length !== 3) {
          return true
        }
        return false
      },
      //  获取商品分类ID
      isGoodsId () {
        if (this.selectdKeys.length === 3) {
          return this.selectdKeys[2]
        }
        return null
      }


    },
  }
</script>

<style lang="less" scoped>
.el-cascader{
  width: 300px;
}
.input-new-tag{
  width: 150px;
}
</style>
